<template>
  <div>
    <Portal to="right-disable" v-if="isShow"
            :disabled="!queryModelDefaultSetting.showSetting"
            v-loading="loading || beforeLoading || loading1 || loading2">
      <DashboardInterceptConsumer :gadgetId="id"
                                  :style="{height: $route.path==='/nextTicket'?'100vh':'80vh','position':'relative'}"
                                  :beforeLoading.sync="beforeLoading"
                                  :beforeIntercept="beforeIntercept">
        <div style="height: 100%;">
          <el-card shadow="never"
                   class="box-card">
            <next-ticket-search :id="id"
                                :nextTicketType="nextTicketType"
                                :gadgetSetting="gadgetSetting"
                                :infoLength="infoLength"
                                :showGrid="showGrid"
                                :currentTemplateId="currentTemplateId"
                                :optionsId="optionsId"
                                :searchIdentifier="searchIdentifier"
                                :nextTicketInfo="nextTicketInfo"
                                @changeTemplate="changeTemplate"
                                @changeFilter="changeFilter"
                                @changeUser="changeUser"
                                @changeLayout="changeLayout"
                                @getDataList="getDataList">
            </next-ticket-search>
            <el-row>
              <div class="line"></div>
              <div class="header_settings">
                <span v-if="$route.path!=='/nextTicket'" style="display: inline-block;margin-left:20px;margin-top: 10px;background: #E6F7FF;padding: 7px 16px;">This is the highest priority ticket that you should work on, based the current ticket filter and <span @click="desSetingPage"
                        style="display: inline-block;border-bottom:1px solid;cursor: pointer;color: #138DC7;">priority rules.</span></span>
                <span v-else style="display: inline-block;margin-left:20px;margin-top: 10px;background: #E6F7FF;padding: 7px 16px;">This is the highest priority ticket that you should work on, based the current ticket filter and priority rules.</span>
                <div class="settings_filter"
                     v-if="showGrid">
                  <el-popover placement="bottom"
                              width="200"
                              v-model="FilterPop"
                              popper-class="fliter_next_pop"
                              trigger="click">
                    <img slot="reference"
                         :src="$ossLink+'/app/nextticket/NextTicketSettings_filter.png'"
                         alt="">
                    <div class="fliter_next_pop_top">
                      <p>Only show tickets that has a point in this range:</p>
                      <div class="fliter_next_pop_content"
                           v-loading="filterLoading">
                        <el-input placeholder="Minimum"
                                  v-model="ptsMin">
                        </el-input>
                        <span>-</span>
                        <el-input placeholder="Maximum"
                                  v-model="ptsMax">
                        </el-input>
                      </div>
                    </div>
                    <div class="fliter_next_pop_footer"
                         @click="comfrimFilter">Save as default</div>
                  </el-popover>
                  <el-popover placement="bottom"
                              width="200"
                              v-model="formatPop"
                              popper-class="format_next_pop"
                              trigger="click">
                    <img slot="reference"
                         :src="$ossLink+'/app/nextticket/NextTicketSettings_format.png'"
                         alt="">
                         <ConditionSetting  v-if="queryModelDefaultSetting.dataInfo.gadgetSetting"
                                    ref="condition-setting"
                                    :allValueLists="allValueLists"
                                    :conditionFieldList="conditionFieldList"
                                    :ruleList.sync="ruleList"
                                    :dataInfoCondition="queryModelDefaultSetting.dataInfo"></ConditionSetting>
                    <div class="format_next_pop_footer">
                      <span @click="saveForamtRule">Save as default</span>
                    </div>
                  </el-popover>
                </div>
              </div>
            </el-row>
            <div v-show="noData">
              <el-row :gutter="20">
                <el-col :span="14"
                        v-if="!showGrid&&nextTicketInfo"
                        class="span14"
                        v-loading="dataLoading">
                  <now-ticket class="el-card-panding"
                              :nextTicketType="nextTicketType"
                              :nextTicketInfoCopy="nextTicketInfo"></now-ticket>
                  <initial-description ref="initial-description"
                                       :nextTicketType="nextTicketType"
                                       :nextTicketInfo="nextTicketInfo"
                                       class="el-card-panding" />
                  <notes-description ref="notes-description"
                                     :nextTicketType="nextTicketType"
                                     :nextTicketInfo="nextTicketInfo"
                                     class="el-card-panding" />
                </el-col>
                <el-col :span="10"
                        v-if="!showGrid&&nextTicketInfo"
                        class="span10"
                        v-loading="dataLoading">
                  <total-points :nextTicketInfo="nextTicketInfo"
                                :nextTicketType="nextTicketType"
                                :gadgetSetting="gadgetSetting"
                                class="el-card-panding2" />
                  <company-info-syncro v-if="nextTicketType.replace('dataset','')  === 'syncro'"
                                       :nextTicketType="nextTicketType"
                                       :nextTicketInfoCopy="nextTicketInfo"
                                       :noteData="noteData"
                                       class="el-card-panding-companyInfo">
                  </company-info-syncro>
                  <div v-else-if="nextTicketType.replace('dataset','')  === 'jira'"></div>
                  <div v-else-if="nextTicketType.replace('dataset','')  === 'halo'"></div>
                  <companyInfo v-else
                               :nextTicketType="nextTicketType"
                               :nextTicketInfoCopy="nextTicketInfo"
                               class="el-card-panding-companyInfo" />
                </el-col>
                <el-col :span="24"
                        v-show="!showGrid">
                  <ScheduledAutoTask ref="scheduled-autotask"
                                     v-if="nextTicketType.replace('dataset','')  === 'autotask'"
                                     :nextTicketInfo="nextTicketInfo"
                                     :nextTicketType="nextTicketType"
                                     :searchIdentifier="searchIdentifier"
                                     class="el-card-pandinglast" />
                  <scheduled-task ref="scheduled-task"
                                  v-if="nextTicketType.replace('dataset','')  === 'nextTicket'"
                                  :nextTicketInfo="nextTicketInfo"
                                  :nextTicketType="nextTicketType"
                                  :searchIdentifier="searchIdentifier"
                                  class="el-card-pandinglast" />
                </el-col>
                <el-col :span="24"
                        v-show="!showGrid">
                  <ticketScheduleTask ref="ticket-scheduleTask"
                                      :nextTicketInfo="nextTicketInfo"
                                      v-if="nextTicketType.replace('dataset','')  === 'nextTicket'"
                                      :searchIdentifier="searchIdentifier"
                                      class="el-card-pandinglast" />
                  <ticket-schedule-task-syncro ref="ticket-scheduleTask"
                                               v-if="nextTicketType.replace('dataset','')  === 'syncro'"
                                               :nextTicketInfo="nextTicketInfo"
                                               :searchIdentifier="searchIdentifier"
                                               :noteData="noteData"
                                               class="el-card-pandinglast">
                  </ticket-schedule-task-syncro>
                  <ticketScheduleTaskaseyabms
                      ref="ticket-scheduleTask"
                      v-if="nextTicketType.replace('dataset','')  === 'kaseyabms'"
                      :nextTicketInfo="nextTicketInfo"
                      :searchIdentifier="searchIdentifier"
                      :noteData="noteData"
                      class="el-card-pandinglast">
                  </ticketScheduleTaskaseyabms>
                  <ticketScheduleTaskjira
                      ref="ticket-scheduleTask"
                      v-if="nextTicketType.replace('dataset','')  === 'jira'"
                      :nextTicketInfo="nextTicketInfo"
                      :searchIdentifier="searchIdentifier"
                      :noteData="noteData"
                      class="el-card-pandinglast">
                  </ticketScheduleTaskjira>
                </el-col>
                <el-col :span="24"
                        v-if="showGrid"
                        v-loading="dataLoading">
                  <NextTicketDataGrid ref="ticket-data-grid"
                                      v-if="!dataLoading"
                                      :key="transmitRuleList"
                                      :nextTicketType="nextTicketType"
                                      :pts="pts"
                                      @updateAllValueList="updateAllValueList"
                                      :conditionFieldList.sync="conditionFieldList"
                                      :ruleList="transmitRuleList"
                                      :nextTicketAllInfo="nextTicketAllInfo"
                                      :customer="noteData.customer"
                                      :nextTicketGadgetSetting="gadgetSetting"
                                      v-loading="loading" />
                </el-col>
              </el-row>
            </div>
            <div v-show="!noData">
              <div style="height: 80vh;background: #fff;">
                <div style="display: flex;justify-content: center ;align-items:center;margin-top:90px;">
                  <img src='@/assets/ticket/nocontent.png'
                       style="height:98px;width:162px;" />
                </div>
                <div style="display: flex;justify-content: center ;align-items:center;margin-top:20px;">
                  <span style="font-weight: 400;color: rgba(0, 0, 0, 0.25);font-size:12px;">{{$t('custom.component.gadget.selectFilter')}}</span>
                </div>
                <div style="display: flex;justify-content: center ;align-items:center;margin-top:10px;">
                  <span style="font-weight: 400;color: rgba(0, 0, 0, 0.25);font-size:12px;">{{$t('custom.component.gadget.dropdownUser')}}</span>
                </div>
                <div style="display: flex;justify-content: center ;align-items:center;margin-top:10px;">
                  <br /><span style="font-weight: 400;color: rgba(0, 0, 0, 0.25);font-size:12px;">{{$t('custom.component.gadget.startDispatching')}}</span>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </DashboardInterceptConsumer>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting" />
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import companyInfo from './components/companyInfo'
import companyInfoSyncro from './components/companyInfoSyncro'
import NotesDescription from './components/NotesDescription'
import InitialDescription from './components/InitialDescription'
import ScheduledTask from './components/ScheduledTask'
import ScheduledAutoTask from './components/ScheduledAutoTask'
import ticketScheduleTask from './components/ticketScheduleTask'
import ticketScheduleTaskSyncro from './components/ticketScheduleTaskSyncro'
import ticketScheduleTaskaseyabms from './components/ticketScheduleTaskkaseyabms'
import ticketScheduleTaskjira from './components/ticketScheduleTaskjira'
import ticketScheduleTaskAuto from './components/ticketScheduleTaskAuto'
import TotalPoints from './components/TotalPoints'
import filterPreviewDialog from './components/filterPreviewDialog'
import NextTicketDataGrid from './components/NextTticketDataGrid'
import { filterJson } from '@/components/next-ticket-filter/filter-json'
import { get } from 'lodash'
import nextTicketSearch from '@/components/gadget/next-ticket-view/components/next-ticket-search'
import nowTicket from './components/nowTicket/index'
import ConditionSetting from './components/condition-setting'
import { getNextAppInfo,getNextAppAllInfo } from '@/utils/common'
import { getUserInfoCommon, getPermissionsCommon } from '@/utils/common-request'
export default ({
  mixins: [mixinGadgetViewModule],
  components: {
    NotesDescription,
    ScheduledTask,
    TotalPoints,
    InitialDescription,
    NextTicketDataGrid,
    ScheduledAutoTask,
    companyInfo,
    companyInfoSyncro,
    filterPreviewDialog,
    ticketScheduleTask,
    ticketScheduleTaskAuto,
    ticketScheduleTaskSyncro,
    ticketScheduleTaskaseyabms,
    nextTicketSearch,
    nowTicket,
    ConditionSetting,
    model: () => import('@/components/gadget/query-model/query-model'),
    ticketScheduleTaskjira
  },
  data: function () {
    return {
      filterLoading: false,
      ruleList: [],
      transmitRuleList: [],
      ruleForm: {
        ruleMax: undefined,
        ruleMin: undefined
      },
      rules: {
        ruleMax: [
          { required: true, message: '', trigger: 'blur' }
        ],
        ruleMin: [
          { required: true, message: '', trigger: 'blur' }
        ]
      },
      colorSelect: [
        {
          color: '#FFA39E',
          select: true
        },
        {
          color: '#FFBB96',
          select: false
        },
        {
          color: '#FFE58F',
          select: false
        },
        {
          color: '#B7EB8F',
          select: false
        },
        {
          color: '#87E8DE',
          select: false
        },
        {
          color: '#91D5FF',
          select: false
        },
        {
          color: '#D3ADF7',
          select: false
        },
        {
          color: '#FFADD2',
          select: false
        }
      ],
      addRulePop: false,
      formatPop: false,
      FilterPop: false,
      pts: {},
      ptsMin: undefined,
      ptsMax: undefined,
      showGrid: this.$route.path!=='/nextTicket'&&localStorage.getItem('showGrid') === 'true',
      loading: false,
      dataLoading: false,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'nextticketviewgadget',
          gadgetSettingExclude: ['DATA'],
          maxRecords: '25',
          conditionFormat: [],
          gadgetSetting: {
            keyArray: [{
              label: '',
              value: '',
              type: 'text'
            }]
          }
        }
      },
      filterSetting: {
        scriptItem: filterJson,
        dataForm: {
          'filters': {
            'rules': [
              {
                'key': '',
                'opt': '',
                'type': 'text',
                'value': ''
              }
            ],
            'condition': 'and'
          }
        },
        queryParams: 'conditions',
        watermark: 'Select a Filter'
      },
      nextTicketInfo: null,
      nextTicketAllInfo: null,
      dialogVisible: false,
      filterIndex: -1,
      isSave: true,
      filterStr: '',
      filterName: '',
      // value: '',
      conditions: '',
      optionsId: null,
      optionItem: null,
      postConditions: null,
      infoLength: 0,
      searchIdentifier: '',
      noData: false,
      rejectDialogVisible: false,
      reason: '',
      beforeLoading: false,
      currentTemplateId: null,
      noteData: {
        customer: {}
      },
      loading1: false,
      conditionFieldList: [],
      allValueLists: {},
      nextTicketType: '',
      loading2:false,
      isShow: false
    }
  },
  props: {
    // nextTicketType: {
    //   type: String,
    //   default: null
    // }
    nextTicketInfoForNt: {
      type:Object,
      default:()=>{}
    }
  },
  watch: {
    nextTicketAllInfo (val) {
      if (val) {
        this.infoLength = val.length
      }
    },
    ruleList (value) {
    }
  },
  computed: {
    value () {
      if (this.optionsId) {
        return this.options.find(e => e.id === this.optionsId)
      }
    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    if(this.$route.path==='/nextTicket') {
      // this.loading = true
      Promise.all([
        getUserInfoCommon(),
        getPermissionsCommon(),
        this.$store.dispatch('getNextTicketAppList'),
        this.$store.dispatch('getNextTicketAppListForNt')
      ]).then(() => {
        this.nextTicketType = this.getNextAppInfo()
        this.getMaxRecordsNum()
        this.getConfigList()
        this.query()
        this.gadgetHeight = (this.gadgetInfo.h * 20) - 20
      })
    }else {
      this.nextTicketType = this.getNextAppInfo()
        this.getMaxRecordsNum()
        this.getConfigList()
        this.query()
        this.gadgetHeight = (this.gadgetInfo.h * 20) - 20
    }
  },
  beforeDestroy () {
    this.$root.eventBus.$off('event:selectFormatColumn')
  },
  methods: {
    getMaxRecordsNum () {
      const params = {
        'key': this.nextTicketType
      }
      this.loading2 = true
      this.$interface.nextTicket.getMaxRecordsNum(params)
        .then(({ data: res }) => {
          this.isShow = true
          this.loading2 = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if(res.data) {
            this.maxRecordsNum = res.data.pageSize
            if(res.data.dataSource) {
              this.nextTicketType = res.data.dataSource
            }
          }
        })
        .catch((e) => {
          this.isShow = true
          this.loading2 = false
          return this.$message.error(e.msg)
        })
    },
    getNextAppInfo () {
      return getNextAppInfo('resourceId', 'nextTicketType')
    },
    changeTemplate (val) {
      if (val.val !== this.currentTemplateId) {
        this.currentTemplateId = val.val
        if (this.searchIdentifier) {
          this.getDataList()
        }
        // if (val.val && this.searchIdentifier) {
        //   if (val.optionItem) {
        //     this.currentTemplateId = val.val
        //     this.getDataList()
        //   }
        // } else if (val.val === null && this.searchIdentifier) {
        //   this.currentTemplateId = null
        //   this.getDataList()
        // }
      }
    },
    changeFilter (val) {
      this.optionItem = val.optionItem
      if (val.val !== this.optionsId) {
        this.optionsId = val.val
        if (val && this.searchIdentifier) {
          this.conditions = val.optionItem.filterStr
          this.getDataList()
        }
        // this.getTicketFilterParams()
      }
    },
    changeUser (val) {
      if (val !== this.searchIdentifier) {
        this.searchIdentifier = val
        // this.localStorageCwUser()
        if (val && this.optionsId) {
          this.getDataList()
        }
      }
    },
    changeLayout () {
      this.changeswich()
    },
    closeRulePop () {
      this.addRulePop = false
      this.$refs['ruleForm'].clearValidate()
      this.ruleForm = {
        ruleMax: undefined,
        ruleMin: undefined
      }
      this.colorSelect.forEach(element => { element.select = false })
      this.colorSelect[0].select = true
    },
    commitRuleForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addRuleList()
          this.closeRulePop()
        } else {
          return false
        }
      })
    },
    saveForamtRule () {
      let params = {
        type: 2,
        config: this.ruleList
      }
      this.updateConfig(params)
    },
    getConfigList () {
      this.$interface.apiManager.getPageConfigList().then(({ data: res }) => {
        this.filterLoading = false
        if (res.data && res.data.length > 0) {
          res.data.forEach(element => {
            if (element.type === 1) {
              this.pts = element.config
              this.ptsMin = element.config.min
              this.ptsMax = element.config.max
            }
            if (element.type === 2) {
              this.ruleList = element.config
              this.transmitRuleList = element.config
              this.queryModelDefaultSetting.dataInfo.conditionFormat = element.config
            }
          })
        }
      }).catch(() => { this.filterLoading = false })
    },
    comfrimFilter () {
      let params = {
        type: 1,
        config: {
          min: this.ptsMin ? this.ptsMin : '',
          max: this.ptsMax ? this.ptsMax : ''
        }
      }
      this.updateConfig(params)
    },
    updateConfig (params) {
      this.filterLoading = true
      this.$interface.apiManager.savePageConfig(params).then(({ data: res }) => {
        this.getConfigList()
        this.FilterPop = false
        this.formatPop = false
      }).catch(() => {
        this.FilterPop = false
        this.formatPop = false
      })
    },
    addRuleList () {
      let item = this.colorSelect.find(e => e.select)
      this.ruleList.push({
        min: this.ruleForm.ruleMin,
        max: this.ruleForm.ruleMax,
        color: item.color
      })
    },
    deleteRule (index) {
      this.ruleList.splice(index, 1)
    },
    selectPointColor (item) {
      this.colorSelect.forEach(element => { element.select = false })
      item.select = true
    },
    desSetingPage () {
      this.$router.push({
        path: `/NextTicketPriorityRules-${this.nextTicketType.replace('dataset','')}?name=NextTicket For ${getNextAppInfo('resourceId', 'nextTicketName')} Priority Rules`
      })
      // switch (this.nextTicketType) {
      //   case 'autotask':
      //     this.$router.push({
      //       path: '/NextTicketForAutotaskPriorityRules'
      //     })
      //     break
      //   case 'nextTicket':
      //     this.$router.push({
      //       path: '/NextTicketForConnectWisePriorityRules'
      //     })
      //     break
      //   case 'syncro':
      //     this.$router.push({
      //       path: '/NextTicketForSyncroPriorityRules'
      //     })
      //     break
      //   case 'kaseyabms':
      //     this.$router.push({
      //       path: '/NextTicketForKaseyaBMSPriorityRules'
      //     })
      //     break
      //   default:
      // }
    },
    handlePreview () {
      this.$root.eventBus.$emit('filterPreviewDialogUpdateFilter')
    },
    // localStorageCwUser () {
    //   switch (this.nextTicketType) {
    //     case 'autotask':
    //       this.$store.commit('AUTONEXTTICKETUSER', this.searchIdentifier)
    //       break
    //     case 'nextTicket':
    //       this.$store.commit('NEXTTICKETUSER', this.searchIdentifier)
    //       break
    //     case 'syncro':
    //       this.$store.commit('SYNCRONEXTTICKETUSER', this.searchIdentifier)
    //       break
    //     case 'kaseyabms':
    //       this.$store.commit('KASEYABMSNEXTTICKETUSER', this.searchIdentifier)
    //       break
    //     default:
    //   }
    // },
    // getTicketFilterParams () {
    //   switch (this.nextTicketType) {
    //     case 'autotask':
    //       this.$store.commit('AUTONEXTTICKETFILTERID', this.optionsId)
    //       break
    //     case 'nextTicket':
    //       this.$store.commit('NEXTTICKETFILTERID', this.optionsId)
    //       break
    //     case 'syncro':
    //       this.$store.commit('SYNCRONEXTTICKETFILTERID', this.optionsId)
    //       break
    //     case 'kaseyabms':
    //       this.$store.commit('KASEYABMSNEXTTICKETFILTERID', this.optionsId)
    //       break
    //     default:
    //   }
    // },
    saveFilters () {
      if (this.filterName.length === 0 && this.filterName.match(/^[ ]*$/)) {
        this.$message.error('FilterName Is required.')
        return false
      }
      if (this.$refs.typeFilter.checkdataArr()) {
        this.dialogVisible = false
        this.isSave = true
      }
    },
    changeswich () {
      this.showGrid = !this.showGrid
      localStorage.setItem('showGrid', this.showGrid)
      this.$nextTick(() => {
        if (!this.showGrid && this.nextTicketAllInfo && this.nextTicketAllInfo.length > 0) this.implementChrenInitData(this.nextTicketAllInfo)
      })
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - 20
      this.gadgetWidth = newWPx
    },
    async beforeIntercept () {
      // if (this.nextTicketType === 'syncro' || this.nextTicketType === 'kaseyabms') {
      //   return 0
      // }
      const { appUserRight, selectDashboardByAppId } = this.$interface.pay
      let appId = get(this.$route, 'query.appId')

      if (this.$route.name === 'home') {
        appId = getNextAppAllInfo('resourceId', 'nextTicketType').appId
      }
      if (!appId) {
        const pageid = this.pageId
        let { data: res } = await selectDashboardByAppId(pageid)

        if (res.data && res.data.length) {
          appId = res.data[0].appId
        }
      }
      const { data: response } = await appUserRight({
        appId
      })

      return response.code
    },
    query () {
      this.loading1 = true
      this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      var _self = this
      if(this.$route.path === '/nextTicket') {
        var param = {
          appId:this.$route.query.appId,
          name:this.$route.query.name,
          subscriptionId:'undefined',
          subscriptionStatus:'undefined',
          gadgetId:getNextAppInfo('resourceId','gadgetId'),
          pageId:this.$route.query.pageid,
          code:"No integration",
          gadgettype:"nextticketviewgadget"
        }
      }else {
        var param = {
          ...this.slicer,
          gadgetId: _self.id,
          pageId: _self.pageId,
          code: this.code,
          gadgettype: this.wgadgettype
        }
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        if (res.config) {
          _self.gadgetSetting = _self._.merge(_self.gadgetSetting, res.config)
        }
        this.getKeyList(_self.gadgetSetting)
        // this.getDataList()
        this.loading1 = false
      }).catch(() => {
        this.loading1 = false
      })
    },
    getKeyList (data) {
      if (data) {
        this.filterSetting.scriptItem.keyArray = data.keyArray
      }
    },
    getDataList () {
      const _self = this
      if (!this.optionsId) {
        if (this.nextTicketType.replace('dataset','')  === 'autotask' && this.nextTicketType.replace('dataset','')  === 'nextTicket') {
          return this.$message.error('Please select a filter before click on "Request Next Ticket" button')
        }
      }
      if (!this.searchIdentifier) {
        return this.$message.error('Please select a user before click on "Request Next Ticket" button')
      }
      if (!this.optionItem) {
        return false
      }
      if(this.nextTicketType.includes('dataset')) {
        this.conditions = this.optionItem.filterDatasetStr
      }else {
        this.conditions = this.optionItem.filterStr
      }
      _self.loading = true
      _self.dataLoading = true
      // conditions: 'id = 390128 ',
      if (this.nextTicketType  === 'autotask') {
        let currFilterJson = []
        this.optionItem.filterJson.rules.forEach(element => {
          currFilterJson.push({
            op: element.opt,
            field: element.key,
            value: element.value
          })
        })
        let param = {
          // queryBody: '{"filter":[{"op":"eq","field":"id","value":"373863"}],"maxRecords":25}',
          queryBody: this.conditions,
          identifier: this.searchIdentifier,
          ruleIds: null,
          modelId: this.currentTemplateId || 0,
          filterId: this.optionsId
        }
        this.$interface.nextTicket.getAutoNtGradingDataListAPI(param, { clientCode: this.$store.state.user.tenantCode }).then(({ data: res }) => {
          this.handelGradingData(res)
        }).catch(() => {
          _self.loading = false
          _self.dataLoading = false
        })
      } else if (this.nextTicketType  === 'nextTicket') {
        this.conditions = this.optionItem.filterStr
        let param1 = {
          // ...this.slicer,
          conditions: this.conditions ? this.conditions : '',
          clientCode: this.$store.state.user.tenantCode,
          identifier: this.searchIdentifier ? this.searchIdentifier : '',
          maxRecords: Number(_self.gadgetSetting.maxRecords) ? Number(_self.gadgetSetting.maxRecords) : this.queryModelDefaultSetting.dataInfo.gadgetSetting.maxRecords,
          modelId: this.currentTemplateId || 0,
          filterId: this.optionsId
        }
        if(this.optionItem.customFieldFilterStr) {
          param1.customFieldConditions = this.optionItem.customFieldFilterStr
        }
        this.$interface.nextTicket.getNtGradingDataListAPI(param1).then(({ data: res }) => {
          this.handelGradingData(res)
        }).catch(() => {
          _self.loading = false
          _self.dataLoading = false
        })
      } else if (this.nextTicketType  === 'syncro') {
        let params = {
          queryBody: JSON.parse(this.conditions),
          identifier: this.searchIdentifier ? this.searchIdentifier : '',
          modelId: this.currentTemplateId || 0,
          ruleIds: null,
          filterId:this.optionItem.id
        }
        this.$interface.nextTicket.getSyncroGradingDataListAPI(params, this.$store.state.user.tenantCode).then(({ data: res }) => {
          this.handelGradingData(res)
        }).catch(() => {
          _self.loading = false
          _self.dataLoading = false
        })
      } else if (this.nextTicketType  === 'kaseyabms') {
        let params = {
          queryBody: JSON.parse(this.conditions),
          identifier: this.searchIdentifier ? this.searchIdentifier : '',
          ruleIds: null,
          filterId:this.optionItem.id
        }
        if (this.currentTemplateId) {
          params.modelId = this.currentTemplateId
        }
        this.$interface.nextTicket.getkaseyabmsGradingDataListAPI(params, this.$store.state.user.tenantCode).then(({ data: res }) => {
          this.handelGradingData(res)
        }).catch(() => {
          _self.loading = false
          _self.dataLoading = false
        })
      } else {
        let params = {
          queryBody: JSON.parse(this.conditions),
          identifier: this.searchIdentifier ? this.searchIdentifier : '',
          ruleIds: null,
          filterId:this.optionItem.id
        }
        if (this.currentTemplateId) {
          params.modelId = this.currentTemplateId
        }
        this.$interface.nextTicket.getGradingDataListAPI(params, this.$store.state.user.tenantCode, this.nextTicketType).then(({ data: res }) => {
          this.handelGradingData(res)
        }).catch(() => {
          _self.loading = false
          _self.dataLoading = false
        })
      }
    },
    handelGradingData (res) {
      if (res.code !== 0) {
        this.loading = false
        this.dataLoading = false
        return this.$message.error(res.msg)
      }
      if (res.data.length > 0) {
        this.noData = true
        this.nextTicketInfo = res.data[0]
        this.$store.commit('STOREAUTOLINK', res.data[0].entity.link)
        this.nextTicketAllInfo = res.data
        this.getTimeEntryListData()
        this.$nextTick(() => {
          this.implementChrenInitData(res.data)
        })
      } else {
        this.nextTicketInfo = null
        this.$store.commit('STOREAUTOLINK', '')
        this.nextTicketAllInfo = []
        this.noData = false
        this.$message.error('No Tickets Available. Try changing your filter conditions to proceed.')
      }
      this.loading = false
      this.dataLoading = false
    },
    implementChrenInitData (data) {
      if (this.showGrid) return
      this.$refs['initial-description'].initData(this.nextTicketType === 'jira'?this.nextTicketInfo.entity.id:this.nextTicketInfo.id)
      this.$refs['notes-description'].initData(this.nextTicketType === 'jira'?this.nextTicketInfo.entity.id:this.nextTicketInfo.id)
      if (this.$refs['scheduled-autotask']) this.$refs['scheduled-autotask'].initData(this.searchIdentifier)
      if (this.$refs['scheduled-task']) this.$refs['scheduled-task'].initData(this.nextTicketType === 'jira'?data[0].entity.id:data[0].id)
      // if (this.$refs['ticket-scheduleTaskAuto']) this.$refs['ticket-scheduleTaskAuto'].initData(this.nextTicketType === 'jira'?data[0].entity.id:data[0].id)
      if (this.$refs['ticket-scheduleTask']) this.$refs['ticket-scheduleTask'].initData(this.nextTicketType === 'jira'?data[0].entity.id:data[0].id)
    },
    getTimeEntryListData (ticketId) {
      if (this.nextTicketType.replace('dataset','')  === 'syncro') {
        const params = {
          tenantCode: this.$store.state.user.tenantCode,
          ticketId: this.nextTicketInfo.id,
          type: this.nextTicketType
        }
        if (this.nextTicketType.replace('dataset','')  === 'autotask' || this.nextTicketType.replace('dataset','')  === 'syncro' || this.nextTicketType.replace('dataset','')  === 'kaseyabms') {
          this.$interface.apiManager.getAutoTaskTicketNotes(params, this.$store.state.user.tenantCode, this.nextTicketInfo.id).then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.noteData = res.data.ticket
          })
        }
      }
    },
    updateAllValueList (obj) {
      this.allValueLists = obj
    }
  }
})
</script>
<style lang="scss">
.format_next_pop_Arule {
  padding: 0;
  .format_next_pop_Arule_header {
    height: 54px;
    padding: 13px 16px 13px 15px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    box-shadow: inset 0px -1px 0px 0px #f0f0f0;
    > div:nth-child(1) {
      width: 28px;
      height: 28px;
      line-height: 28px;
      text-align: center;
    }
    > div:nth-child(3) {
      width: 28px;
      height: 28px;
      line-height: 28px;
      text-align: center;
    }
    > div:nth-child(2) {
      flex: 1;
      color: #404040;
      font-size: 16px;
    }
    > div:nth-child(3):hover {
      background-color: #e6f7ff;
      cursor: pointer;
    }
    > div:nth-child(1):hover {
      background-color: #e6f7ff;
      cursor: pointer;
    }
  }
  .format_next_pop_Arule_content {
    height: 142px;
    padding: 8px 16px;
    .format_next_pop_Arule_content_pointsetting {
      height: 68px;
      .pointsetting_content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .el-form {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
        }
        .el-form-item {
          margin: 0;
        }
        .el-input {
          width: 116px;
          height: 30px;
          .el-input__inner {
            height: 30px;
          }
        }
      }
      .pointsetting_text {
        font-size: 14px;
        color: #404040;
        margin-bottom: 8px;
      }
    }
    .format_next_pop_Arule_content_color {
      height: 58px;
      .content_color_text {
        font-size: 14px;
        color: #404040;
        margin-bottom: 8px;
      }
      .content_color_select {
        display: flex;
        justify-content: space-between;
        align-items: center;
        > div {
          width: 20px;
          height: 20px;
          text-align: center;
          line-height: 20px;
          cursor: pointer;
        }
        > div::before {
          color: #fff;
        }
      }
    }
  }
  .format_next_pop_Arule_footer {
    height: 64px;
    padding: 16px;
    button {
      width: 100%;
      background-color: #138dc7;
    }
    button:hover {
      opacity: 0.9;
    }
  }
}
.format_next_pop {
  width: 360px !important;
  margin-left: -40px;
  padding: 0;
  .format_next_pop_add {
    height: 46px;
    border-bottom: 1px solid #f0f0f0;
    line-height: 46px;
    padding-left: 16px;
    color: #138dc7;
    font-size: 14px;
    span {
      cursor: pointer;
    }
  }
  .format_next_pop_content {
    height: 136px;
    box-shadow: inset 0px -1px 0px 0px #f0f0f0;
    padding: 8px 8px 8px 16px;
    overflow-y: auto;
    .format_next_pop_content_item {
      // height: 40px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      font-size: 10px;
      > div:nth-child(1) {
        width: 24px;
        height: 24px;
        background-color: #91d5ff;
        margin-right: 8px;
      }
      > div:nth-child(2) {
        flex: 1;
        word-break: break-word;
        span {
          transform: scale(0.83);
        }
      }
      > div:nth-child(3) {
        width: 28px;
        height: 28px;
        line-height: 28px;
        text-align: center;
      }
      > div:nth-child(3):hover {
        background-color: #e6f7ff;
        cursor: pointer;
      }
    }
  }
  .format_next_pop_footer {
    border-top: 1px solid #f0f0f0;
    height: 46px;
    color: #138dc7;
    font-size: 14px;
    line-height: 46px;
    margin: 8px 0;
    padding-left: 16px;
    span {
      cursor: pointer;
    }
  }
}
.fliter_next_pop {
  width: 314px !important;
  // height: 128px !important;
  padding: 0;
  p {
    word-break: keep-all;
    font-size: 12px;
    margin: 0;
    margin-bottom: 8px;
  }
  .fliter_next_pop_top {
    height: 82px;
    padding: 16px;
  }
  .fliter_next_pop_content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-input {
      width: 116px;
      height: 30px;
    }
  }
  .fliter_next_pop_footer {
    height: 30px;
    margin: 8px 0 10px 0;
    padding-left: 16px;
    color: #138dc7;
    line-height: 30px;
    cursor: pointer;
  }
}
</style>
<style scoped>
::v-deep .el-input__inner {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.el-select ::v-deep {
  width: 100%;
}
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}
.el-card-panding {
  padding: 20px 20px 0px !important;
}
.el-card-panding-companyInfo {
  padding: 20px 20px 0px 0 !important;
}
.el-card-panding2 {
  padding-top: 20px !important;
  padding-right: 20px !important;
}
.el-card-pandinglast {
  padding-top: 20px !important;
  padding-right: 20px !important;
  padding-left: 20px !important;
  padding-bottom: 20px !important;
}
.span10 {
  padding-left: 0px !important;
}
.span14 {
  padding-right: 0px !important;
}
.line {
  border-bottom: 1px solid #f0f0f0;
  height: 1px;
}
.header_settings {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header_settings .settings_filter {
  width: 220px;
  height: 28px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.header_settings .settings_filter .settings_filter_items {
  width: 106px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.header_settings .settings_filter > span {
  display: inline-block;
  width: 106px;
  height: 100%;
}
.header_settings .settings_filter > span img {
  width: 106px;
  height: 100%;
  cursor: pointer;
}
.header_settings .settings_filter > span img:hover {
  background-color: #e6f7ff;
}
.header_settings .settings_filter > span:nth-child(1) {
  margin-right: 8px;
}
.header_settings .settings_filter > span:nth-child(2) {
  margin-right: 15px;
}
.swichbuttton {
  width: 64px;
  height: 24px;
  background: #eeeeee;
  border-radius: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  /* margin-left: auto; */
}
.swichbuttton > span {
  width: 30px;
  height: 20px;
  border-radius: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
.swichbuttton1 {
  background: #eeeeee;
  text-align: center;
}
.swichbuttton2 {
  background: #138dc7;
}
.swichbuttton3 {
  background: #138dc7;
}
.swichbuttton4 {
  background: #eeeeee;
  text-align: center;
}
.swichbuttton1 > img {
  width: 14px;
  height: 14px;
}
.swichbuttton2 > img {
  width: 14px;
  height: 14px;
}
.watch_list_entry {
  padding-left: 20px;
  background-image: url("../../../assets/ticket/company_watch/watch list_entry.png");
  background-repeat: no-repeat;
  background-size: 14px;
  background-position: left center;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.5);
}
.vertica_line {
  width: 1px;
  background-color: #f0f0f0;
  height: 24px;
}
.firstIcon {
  height: 24px;
  width: 24px;
  margin-left: 20px;
  margin-bottom: 4px;
  margin-top: 4px;
}
</style>
